 <template>
   <el-card shadow="always" class="box-card">
      <div class="card-name search-item">
        <div class="name width2">新增销售订单</div>
        <div class="mr-15">
          <el-button size="medium" type="primary" @click="addRow">新增</el-button>
          <el-button size="medium" type="warning" @click="saveTable">保存</el-button>
        </div>
      </div>
      <div class="content-con">
        <el-form :model="form" ref="form" size="medium" label-width="110px">
          <el-row :gutter="24" type="flex" justify="start">
            <el-col :span="5">
              <el-form-item label="客户:" prop="client">
                <el-input v-model="form.client" clearable placeholder="客户">
                  <el-button size="mini" slot="append" icon="el-icon-search" @click="open"></el-button>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="销售人员:" prop="user">
                <el-select v-model="form.user" filterable clearable placeholder="销售人员" style="width: 100%;">
                  <el-option
                    v-for="item in userList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="单据日期:" prop="bill_date">
                <el-date-picker
                  v-model="form.bill_date"
                  type="date"
                  format="yyyy-MM-dd"
                  placeholder="单据日期"
                  style="width: 100%;">
                </el-date-picker></el-form-item></el-col>
            <el-col :span="5">
              <el-form-item label="单据编号:" prop="billno">
                <el-input v-model="form.billno" :disabled="true" placeholder="单据编号"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" type="flex" justify="start">
            <el-col :span="5">
              <el-form-item label="联系人:" prop="contact">
                <el-select v-model="form.contact" filterable clearable placeholder="联系人" style="width: 100%;">
                  <el-option
                    v-for="item in contactList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="地址:" prop="address">
                <el-input v-model="form.address" placeholder="地址"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="电话:" prop="phone">
                <el-input v-model="form.phone" placeholder="电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="订单类型:" prop="order_type">
                <el-radio-group v-model="form.order_type">
                  <el-radio :label="0">线上订单</el-radio>
                  <el-radio :label="1">线下订单</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <div class="bank-form">
            <div class="form-item">
              <el-table
                :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                class="table"
                stripe border
                show-summary
                :summary-method="getSummaries"
                @cell-click="editData"
                :row-class-name="tableRowClassName"
                :header-cell-style="{background:'#f3f3f3',textAlign: 'center'}"
                :cell-style="{ textAlign: 'center' }">
                <el-table-column type="index" width="50" fixed>
                </el-table-column>
                <el-table-column prop="goods" label="商品" width="160" fixed>
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '商品'">
                      <el-input v-model="scope.row.goods" size="mini" @blur="inputBlur">
                        <el-button slot="append" type="text"  icon="el-icon-search" @click="openGoods"></el-button>
                      </el-input>
                    </span>
                    <span v-else>{{ scope.row.goods }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" width="100">
                </el-table-column>
                <el-table-column prop="warehouse" label="仓库(批量)" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '仓库(批量)'">
                      <el-input v-model="scope.row.warehouse" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.warehouse }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="数量" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '数量'">
                      <el-input v-model="scope.row.amount" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.amount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="sale_price" label="销售单价" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '销售单价'">
                      <el-input v-model="scope.row.sale_price" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.sale_price }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="discount_rate" label="折扣率(%)" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '折扣率(%)'">
                      <el-input v-model="scope.row.discount_rate" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.discount_rate }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="discount" label="折扣额" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '折扣额'">
                      <el-input v-model="scope.row.discount" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.discount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="sale_amount" label="销售金额(元)" width="120">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '销售金额(元)'">
                      <el-input v-model="scope.row.sale_amount" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.sale_amount }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="produce_date" label="生产日期" width="160">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '生产日期'">
                      <el-input v-model="scope.row.produce_date" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.produce_date }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="indate" label="有效期天数" width="100">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '有效期天数'">
                      <el-input v-model="scope.row.indate" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.indate }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="note" label="备注" width="150">
                  <template slot-scope="scope">
                    <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '备注'">
                      <el-input v-model="scope.row.note" size="mini" @blur="inputBlur"/>
                    </span>
                    <span v-else>{{ scope.row.note }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="220">
                  <template slot-scope="scope">
                    <el-button type="text" @click.native.prevent="deleteRow(scope.$index,tableData)">
                      <i class="el-icon-delete"></i>删除
                    </el-button>
                    <el-button type="text" @click="stockSearch(scope.$index,scope.row)">
                      <i class="el-icon-search"></i>商品库存查询
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!-- 分页-页码 -->
            <div class="page">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="tableData.length">
              </el-pagination>
            </div>
          </div>
          <div class="mt-20">
            <el-form-item label="备注信息:" prop="fnote">
              <el-input type="textarea" v-model="form.fnote" clearable placeholder="暂无备注信息"></el-input>
            </el-form-item>
            <el-row :gutter="24" type="flex" justify="start">
              <el-col :span="5">
                <el-form-item label="优惠率:" prop="premium_rate"><span>
                  <el-input-number style="width: 166px;" :min="0" v-model="form.premium_rate" controls-position="right">
                  </el-input-number>%</span>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="优惠金额:" prop="discount_amount">
                  <el-input v-model="form.discount_amount" clearable placeholder="优惠金额"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="优惠后金额:" prop="after_amount">
                  <el-input v-model="form.after_amount" :disabled="true" placeholder="优惠后金额"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="客户承担费用:" prop="client_bear">
                  <el-input v-model="form.client_bear" clearable placeholder="客户承担费用"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" type="flex" justify="start">
              <el-col :span="5">
                <el-form-item label="本次收款:" prop="collect">
                  <el-input v-model="form.collect" clearable placeholder="本次收款"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="结算账户:" prop="settle_account">
                  <el-select v-model="form.settle_account" filterable clearable placeholder="结算账户" style="width: 100%;">
                    <el-option
                      v-for="item in accountList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="本次欠款:" prop="arrears">
                  <el-input v-model="form.arrears" :disabled="true" placeholder="本次欠款"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
         </el-form>
      </div>
      <modal-client ref="ModalClient"></modal-client>
      <modal-goods ref="ModalGoods"></modal-goods>
      <goods-stock ref="GoodsStock" :rows="rows"></goods-stock>
   </el-card>

 </template>
<script>
import ModalClient from '@/components/client-manage/ModalClient';
import ModalGoods from '@/components/purchasing-system/ModalGoods';
import GoodsStock from '@/components/purchasing-system/GoodsStock';
export default {
  components: {
    ModalClient,
    ModalGoods,
    GoodsStock
  },
  data () {
    return {
      rows: '', //表格一行的数据
      tabClickIndex: null, // 点击的单元格
      tabClickLabel: '', // 当前点击的列名
      currentPage: 1, //当前页码
      pagesize: 10,    //每页的数据条数
      //tableData: [], //表格数据
      form: {
        client: '',
        user: '',
        bill_date: '',
        billno: 'CG202103161536361',
        contact: '',
        address: '',
        phone: '',
        order_type: 0,
        fnote: '',
        premium_rate: '0',
        discount_amount: '0',
        after_amount: '0.00',
        client_bear: '0.00',
        collect: '0.00',
        settle_account: '0',
        arrears: '0.00'
      },
      contactList: [
        {value: '0',label: '（空）'},
        {value: '1',label: '小笑话'}
      ],
      userList: [
        {value: '0',label: '张三'},
        {value: '1',label: '李四'}
      ],
      accountList: [
        {value: '0',label: '（空）'},
        {value: '1',label: '多账户'}
      ],
      tableData: [
        {
          goods: '葡萄',
          unit: 'kg',
          warehouse: '南宁仓库',
          amount: '50',
          sale_price: '5',
          discount_rate: '0',
          discount: '0',
          sale_amount: '100',
          produce_date: '',
          indate: '120',
          note: '啊啊啊'
        }
      ]
    }
  },

  mounted() {
    this.getTime();
  },
  created() {
    // this.tableData.map(i => {
    //   i.show = false
    //   return i
    // })
  },

  methods: {
    //搜索
    search() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          console.log(this.form)
          this.$message.success('成功!');
        } else {
          console.log('error submit!!');
          this.$message.error('失败!');
          return false;
        }
      });
    },

    //客户-对话框
    open() {
      this.$nextTick(()=>{
        this.$refs.ModalClient.openClients();
      });
    },

    //商品-选择-对话框
    openGoods() {
      this.$nextTick(()=>{
        this.$refs.ModalGoods.openGood();
      });
    },

    //商品库存查询
    stockSearch(index, row){
      this.rows = row;
      this.$nextTick(()=>{
        this.$refs.GoodsStock.openStock();
      });
    },

    //添加一行
    addRow() {
      let j = {"goods": '',"unit": '',"warehouse": '',"amount": '',"sale_price": '',"discount_rate": '',"discount": '',"sale_amount": '',"produce_date": '',"indate": '',"note": ''}
      this.tableData.push(j);
      // this.tableData
    },
    //保存
    saveTable() {
      console.log('table', this.tableData)
      console.log('form',this.form)
    },
    //删除操作
    deleteRow(index, rows){
      rows.splice(index, 1);
    },

    tableRowClassName({row,rowIndex}) {
      // 把每一行的索引放进row
       row.index = rowIndex
    },
    // 添加明细原因 row 当前行 column 当前列
    //单元格被单击时
    editData(row, column, cell, event) {
      console.log(row,column)

      switch (column.label) {
        case '商品':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case '仓库(批量)':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case '数量':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case '销售单价':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case '折扣率(%)':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case '折扣额':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case '销售金额(元)':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case '生产日期':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case '有效期天数':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        case '备注':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          break
        default: return
      }
      console.log('商品', this.tabClickIndex, row, column, cell, event)
    },
    // 失去焦点初始化
    inputBlur(row, event, column) {
      this.tabClickIndex = null
      this.tabClickLabel = ''
    },

    //表格合计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = []; //声明变量
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if(
          column.property == "amount" || column.property == "discount" || column.property == "sale_amount"
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          // sums[index]+='元';
        } else {
          // sums[index] = '';
        }
      });
      return sums;
    },

    //获取当前时间
    getTime(){
      let year = new Date().getFullYear(); //获取当前时间的年份
      let month = new Date().getMonth() + 1; //获取当前时间的月份
      let day = new Date().getDate(); //获取当前时间的天数
      //当小于 10 的是时候，在前面加 0
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      //拼接格式化当前时间
      this.form.bill_date = year + "-" + month + "-" + day ;
    },

    //每页条数改变时触发事件,选择一页显示多少行
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pagesize = val;
    },
    // 当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
    }
  }
}
</script>
<style lang="scss">
</style>
